package com.heatingcharge.service.charge.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.dto.ChargeRefundDTO;
import com.heatingcharge.entity.charge.ChargeRefund;
import com.heatingcharge.mapper.charge.ChargeRefundMapper;
import com.heatingcharge.param.ChargeRefundParam;
import com.heatingcharge.param.SearchParam;
import com.heatingcharge.security.JwtUser;
import com.heatingcharge.security.util.JwtUtil;
import com.heatingcharge.security.util.SecurityUtil;
import com.heatingcharge.service.charge.IChargeRefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 退费表 服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-11-20
 */
@Service
public class ChargeRefundServiceImpl extends ServiceImpl<ChargeRefundMapper, ChargeRefund> implements IChargeRefundService {

    @Override
    public IPage<ChargeRefundDTO> getChargeRefund(Page page, SearchParam searchParam) {
        return baseMapper.selectChargeRefund(page, searchParam);
    }

    @Override
    public List<ChargeRefundDTO> getChargeRefund(SearchParam searchParam) {
        return null;
    }

    /**
     * 新增退费
     * @param chargeRefundParam
     * @return
     */
    @Override
    public Integer saveChargeRefund(ChargeRefundParam chargeRefundParam) {
        JwtUser user= SecurityUtil.getUser();
        if (checkExist(chargeRefundParam.getHeatYearId(),chargeRefundParam.getHouseId())){
            throw new BaseException(ResponseCodeEnum.CHARGEREFUND_EXIST.getMessage(),ResponseCodeEnum.CHARGEREFUND_EXIST.getCode());
        }
        ChargeRefund chargeRefund=ChargeRefund.builder()
                .heatYearId(chargeRefundParam.getHeatYearId())
                .houseId(chargeRefundParam.getHouseId())
                .amount(chargeRefundParam.getAmount())
                .mode(chargeRefundParam.getMode())
                .refundDate(chargeRefundParam.getRefundDate())
                .status(0)
                .operator(user.getRealName())
                .remark(chargeRefundParam.getRemark())
                .build();
        return baseMapper.insert(chargeRefund);
    }

    /**
     * 检查是否存在指定用户指定年度的退费信息
     * @param heatYearId
     * @param houseId
     * @return
     */
    private Boolean checkExist(Integer heatYearId,Integer houseId){
        QueryWrapper<ChargeRefund> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("heat_year_id",heatYearId);
        queryWrapper.eq("house_id",houseId);
        return baseMapper.selectList(queryWrapper).size()>0;
    }
}
